<?php
namespace App\Core\App;

use App\Core\Container;
use Exception;

class FpmApp extends BaseApp
{
    /**
     * 默认控制器
     * @var string
     */
    public string $defaultController = 'index';

    /**
     * 默认action
     * @var string
     */
    public string $defaultAction = 'test';

    /**
     * @throws Exception
     */
    public function run()
    {
        //将server对象存入容器
        Container::set('server',$this);
        $controller = $this->defaultController;
        $action = $this->defaultAction;
        if (!empty($_GET['p'])) {
            $pathArr = explode('/', substr($_GET['p'], 1, strlen($_GET['p'])));
            if (count($pathArr) == 1) {
                throw new Exception('api not find path = ' . $_GET['p']);
            }
            $controller = $pathArr[0];
            $action = $pathArr[1];
        }

        $path = $controller . '/' . $action;
        $actionArr = explode('-', $action);
        $action = 'action';
        foreach ($actionArr as $item) {
            $action .= ucfirst($item);
        }
        $controller = ucfirst($controller);

        $controllerClass = '\\App\\FpmControllers\\Fpm' . $controller . 'Controller';
        $controllerFile = __DIR__ . '/../../FpmControllers/Fpm' . $controller . 'Controller.php';
        if (!is_file($controllerFile)) {
            throw new \Exception('api not find(path=' . $path . ')');
        }
        $controller = new $controllerClass;
        if (!method_exists($controller, $action)) {
            throw new \Exception('method not find(path=' . $path . ')');
        }
        $isNextRun = $controller->before();
        if ($isNextRun) {
            $controller->$action();
        }
    }
}
